MERN Stack
Lesson Objectives
- Set up static files
- Set up React using Create React App
- Get Data from our holidays_api app
- Do rest of CRUD
Bootstrap React App using Vite
npm create vite
npm install
npm start
What we're building
We are using the following React Router routes:
/holidays
for the above/holidays/:id/edit
for the edit page
Get Data from Our API
First, we'll need to store our data in the state of our App.
import { useState } from "react";
function App() {
const [holidays, setHolidays] = useState([]);
return (
<div className="container">
<h1>Holidays! Celebrate!</h1>
</div>
);
};
We can use fetch
to make database calls for us, adapting from Using the fetch API
async function fetchHolidays() {
const response = await fetch("http://localhost:3000/api/holidays");
const jsonData = await response.json();
console.log(jsonData);
}
fetchHolidays();
Now in your console you should be able to see your holiday coming back from your backend api!
Show A list of Holidays
Right now we're just calling this fetch on loading of this react app. But we're going to want to be able to call this functionality again and again.
Inside the file App, let's put this code inside a useEffect
. We'll also set up state to hold our array of holidays
import { useEffect, useState } from "react";
function App() {
const [holidays, setHolidays] = useState([]);
useEffect(() => {
async function fetchHolidays() {
const response = await fetch("http://localhost:3000/api/holidays");
const jsonData = await response.json();
console.log(jsonData);
}
fetchHolidays();
}, []);
return (
<div className="container">
<h1>Holidays! Celebrate!</h1>
</div>
);
};
When to call useEffect
We want to call useEffect
when we render the app.
If we put it in the render function, we'll create an infinite loop.
We need a more surefire way to call this function at the right time. React has some lifecycle
methods for exactly this purpose. We may want to run things when a component is mounted on the DOM, when a component is unmounted, when it is updated and more. We will use useEffect(() => {...}, [])
for our purpose
We should still see our holiday(s) from our API console logging.
Now we want to set that data in state
Finally, we want to render it:
<h1>Holidays! Celebrate!</h1>
<table>
<tbody>
{holidays.map((holiday) => {
return (
<tr key={holiday.id}>
<td> {holiday.name}</td>
</tr>
);
})}
</tbody>
</table>
Full Code:
import { useEffect, useState } from "react";
function App() {
const [holidays, setHolidays] = useState([]);
useEffect(() => {
async function fetchHolidays() {
const response = await fetch("http://localhost:3000/api/holidays");
const jsonData = await response.json();
setHolidays(jsonData);
}
fetchHolidays();
}, []);
return (
<div className="container">
<h1>Holidays! Celebrate!</h1>
<table>
<tbody>
{holidays.map((holiday) => {
return (
<tr key={holiday.id}>
<td> {holiday.name}</td>
</tr>
);
})}
</tbody>
</table>
</div>
);
};